package com.cf.docker.websocket;

import com.cf.docker.service.SSHService;
import com.cf.exception.BizException;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@ServerEndpoint("/dev-ssh/{serverIp}/{account}/{pwd}/{reconnect}")
public class WebShellSocket {

    private SSHService sshService = new SSHService();

    private Map<Session, AccountInfo> infoMap = new HashMap<Session, AccountInfo>();

    /**
     * 新的WebSocket请求开启
     */
    @OnOpen
    public void onOpen(Session session,
                       @PathParam("serverIp") String serverIp,
                       @PathParam("account") String account,
                       @PathParam("pwd") String pwd,
                       @PathParam("reconnect") boolean reconnect) throws IOException {
        if (reconnect) {
            if (StringUtils.isNotEmpty(serverIp)) {
                sshService.reconnection(serverIp);
            }
        }

        if (StringUtils.isEmpty(serverIp) || StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
            session.getBasicRemote().sendText("参数缺失！serverIp：account：pwd");
            return;
        }
        try {
            sshService.sendCmd("cat /proc/version", session, serverIp, account, pwd);
        } catch (BizException e) {
            session.getBasicRemote().sendText("连接建立失败！");
            return;
        }
        infoMap.put(session, new AccountInfo(serverIp, account, pwd));
    }


    /**
     * WebSocket请求关闭
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        AccountInfo accountInfo = infoMap.get(session);
        sshService.close(accountInfo.getIp());
        session.getBasicRemote().sendText("关闭ssh连接成功！");
    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        AccountInfo accountInfo = infoMap.get(session);
        try {
            sshService.sendCmd(message, session, accountInfo.getIp(), accountInfo.getAccount(), accountInfo.getPwd());
        } catch (Exception e) {
            session.getBasicRemote().sendText(e.getMessage());
        }
    }

}
